from flask import Flask, request, jsonify
from weibo_video_fetcher_new import start_fetch
from batch_download import batch_download
import subprocess
import platform, os, sys

is_windows = (
    platform.system() == "Windows" 
    or os.name == "nt" 
    or sys.platform.startswith("win")
)


app = Flask(__name__)

@app.route('/fetch_web', methods=['POST'])
def handle_post():
    # 获取POST请求数据
    request_data = request.get_json()
    in_uid = request_data.get("uid", "xxxx")
    print(f"get uid {in_uid}")
    start_fetch(in_uid)
    
    # 构造响应数据
    response = {
        'status': 'success',
    }
    return jsonify(response)

@app.route('/download_img', methods=['POST'])
def download_img():
    print("download_img")
    if not is_windows:
        with subprocess.Popen(["./down.sh"], stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True) as proc:
            for line in proc.stdout:
                print(line.strip())
    else:
        batch_download("result_img.txt", "image", 10)
    
    # 构造响应数据
    response = {
        'status': 'success',
    }
    return jsonify(response)

@app.route('/download_video', methods=['POST'])
def download_video():
    print("download_video")
    if not is_windows:
        with subprocess.Popen(["./down_video.sh"], stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True) as proc:
            for line in proc.stdout:
                print(line.strip())
    else:
        batch_download('result.txt', "video", 4)
    
    # 构造响应数据
    response = {
        'status': 'success',
    }
    return jsonify(response)

@app.route('/update_cookie', methods=['POST'])
def update_cookie():
    request_data = request.get_json()
    in_cookie = request_data.get("cookie", "xxxx")

    header_data = []
    with open("header.txt", "r") as f:
        for i in f.readlines():
            if i.startswith("cookie"):
                header_data.append(f"cookie: {in_cookie}\n")
            else:
                header_data.append(i)
            
    with open("header.txt", "w") as f:
        f.writelines(header_data)

    
    # 构造响应数据
    response = {
        'status': 'success',
    }
    return jsonify(response)

if __name__ == '__main__':
    app.run(port=5000, debug=False)